﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CustomControls_Etapas : System.Web.UI.UserControl
{
    private bool Add
    {
        get
        {
            if (ViewState["add"] != null)
            {
                return (bool)ViewState["add"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["add"] = value;
        }
    }
    private bool Edit
    {
        get
        {
            if (ViewState["Edit"] != null)
            {
                return (bool)ViewState["Edit"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["Edit"] = value;
        }
    }
    private bool View
    {
        get
        {
            if (ViewState["View"] != null)
            {
                return (bool)ViewState["View"];
            }
            else
            {
                return false;
            }
        }
        set
        {
            ViewState["View"] = value;
        }
    }
    protected string uniqueId
    {
        get
        {
            if (Session["uniqueId"] == null)
                Session["uniqueId"] = "";
            return (string)Session["uniqueId"];
        }
        set
        {
            Session["uniqueId"] = value;
        }
    }
    protected long ProcessId
    {
        get
        {
            if (ViewState["ProcessId"] == null) return 0;
            return (long)ViewState["ProcessId"];
        }
        set { ViewState["ProcessId"] = value; }
    }
    protected int StageId
    {
        get
        {
            if (ViewState["StageId"] == null) return 0;
            return (int)ViewState["StageId"];
        }
        set { ViewState["StageId"] = value; }
    }
    protected String[] Message
    {
        get
        {
            if (Session["Message"] == null)
            {
                String[] m = {"",""};
                return m;
            }
            return (String[])Session["Message"];
        }
        set { Session["Message"] = value; }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            fillOrder();
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                uniqueId = Guid.NewGuid().ToString() + "-" + Request.QueryString["id"];
            }
            else
            {
                uniqueId = Guid.NewGuid().ToString();
            }
            
            String[] msg = { "", "" };
            Message = msg;
            int cid = 0;
            int.TryParse(Request.QueryString["processID"], out cid);
            this.ProcessId = cid;
            BLLProcess bll = new BLLProcess();
            Process p = bll.getProcessById(this.ProcessId);
            if (p == null)
            {
                String[] error = { Resources.Resource.ERROR, Resources.Resource.PROCESS_NOT_FOUND };
                Message = error;
                this.Response.Redirect("/Procesos/Etapas/Default.aspx?id" + this.ProcessId);
            }
            if (!String.IsNullOrEmpty(Request.QueryString["Id"]) && Request.Url.ToString().Contains("Editar.aspx") )
            {
                int sid = 0;
                int.TryParse(Request.QueryString["Id"], out sid);
                this.StageId = sid;
                BLLStages bllS = new BLLStages();

                Stage st = bllS.GetStageById(this.StageId);
                if (st != null)
                {
                    bllS.InsertTempDetails(uniqueId, this.StageId);
                    ltrTitle.Text = "Editar Etapa: " + st.Name + " - "+p.Name;
                    populateInfo(st);
                }
                else
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.PROCESS_NOT_FOUND };
                    Message = error;
                    this.Response.Redirect("/Procesos/Etapas/Default.aspx?id"+this.ProcessId);
                }
            }
            else
            {
                if (!String.IsNullOrEmpty(Request.QueryString["id"]))
                {
                    String[] error = { Resources.Resource.ERROR, Resources.Resource.INVALID_URL };
                    Message = error;
                    this.Response.Redirect("/Procesos/Etapas/Default.aspx?id" + this.ProcessId);
                }
                else
                {
                    ltrTitle.Text = "Agregar Etapa: " + p.Name;
                }
            }
            PopulateProductsGrid();
            PopulateAssignedProductsGrid();
            SetupPageByUserRoles();
        }
        ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "0";
    }
    private void populateInfo(Stage p)
    {
        txtName.Text = p.Name;
        txtDescription.Text = p.Observation.Trim();
        txtTemperature.Text = p.Temperature.ToString();
        txtTime.Text = p.Time.ToString();
        txtWater.Text = p.Water.ToString();
        drdOrder.SelectedValue = p.Order.ToString();
    }
    private void fillOrder()
    {
        for (int i = 1; i < 15; i++)
        {
            drdOrder.Items.Add(new ListItem(i.ToString(), i.ToString()));
        }
    }
    protected void buildSelection() 
    {
        List<StageDetailsTemp> products = new List<StageDetailsTemp>();
        foreach (GridViewRow item in grdAssigned.Rows)
        {
            HiddenField hdnId = (HiddenField)item.FindControl("hdnProductId");
            CheckBox chkAssign = (CheckBox)item.FindControl("chkAssignProduct");
            TextBox txtQuantity = (TextBox)item.FindControl("txtQuantity");
            TextBox txtObservation = (TextBox)item.FindControl("txtObservation");
            StageDetailsTemp sd = new StageDetailsTemp();
            sd.Guid = uniqueId;
            long pid = 0;
            long.TryParse(hdnId.Value, out pid);
            sd.ProductId = pid;
            sd.StageId = StageId;
            decimal quantity = 0;
            decimal.TryParse(txtQuantity.Text, out quantity);
            if (String.IsNullOrEmpty(txtQuantity.Text))
                quantity = -1;
            sd.Quantity = quantity;
            sd.Observation = txtObservation.Text;
            sd.CreatedDate = DateTime.Now;
            products.Add(sd);
        }
        BLLStages bllStages = new BLLStages();
        bllStages.UpdateSelection(products, uniqueId);

    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        buildSelection();
        BLLStages bllStages = new BLLStages();
        int result = bllStages.isValidStageDetails(uniqueId, this.StageId);
        if (result == 1)
        {
            Stage Stage = new Stage();
            Stage.Id = this.StageId;
            Stage.CreatedBy = Util.GetCurrentUserId();
            Stage.CreatedDate = DateTime.Now;
            Stage.IsEnabled = true;
            Stage.Name = txtName.Text;
            Stage.Observation = txtDescription.Text;
            Stage.ProcessId = this.ProcessId;
            int temp = 0;
            int.TryParse(txtTemperature.Text, out temp);
            Stage.Temperature = temp;
            int time = 0;
            int.TryParse(txtTime.Text, out time);
            Stage.Time = time;
            int water = 0;
            int.TryParse(txtWater.Text, out water);
            Stage.Water = water;
            int order = 0;
            int.TryParse(drdOrder.SelectedValue, out order);
            Stage.Order = order;
            if (bllStages.SaveStageWithDetails(Stage, uniqueId))
            {
                String[] error = { Resources.Resource.SUCCESS, Resources.Resource.STAGE_CREATED };
                Message = error;
                this.Response.Redirect("~/Procesos/Etapas/Default.aspx?id="+this.ProcessId.ToString());
            }
            else {
                ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.UPDATE_ERROR;
                ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
            }
        }
        else {
            if(result == 0)
            {
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.STAGEDETAILSQUANTITYREQUIRED;
            }
            else
            {
                ((Literal)Page.Master.FindControl("ltrMessage")).Text = Resources.Resource.STAGEDETAILSREQUIRED;
            }
            ((Literal)Page.Master.FindControl("ltrShowMessage")).Text = "1";
            
            ((Literal)Page.Master.FindControl("ltrMessageType")).Text = Resources.Resource.ERROR;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        this.Response.Redirect("~/Procesos/Etapas/Default.aspx?id=" + this.ProcessId.ToString());
    }
    private void PopulateProductsGrid()
    {
        if (!IsPostBack)
        {
            grdProductos.AllowPaging = true;
            grdProductos.AllowSorting = true;
            grdProductos.PageSize = (ConfigurationManager.AppSettings["PageSize"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]) : 10;
            grdProductos.PagerSettings.PageButtonCount = (ConfigurationManager.AppSettings["PageButtonCount"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageButtonCount"]) : 5;
            grdProductos.PagerSettings.FirstPageText = "Primero";
            grdProductos.PagerSettings.LastPageText = "Ultimo";
            grdProductos.PagerSettings.Mode = PagerButtons.NumericFirstLast;
            grdProductos.PagerSettings.Position = PagerPosition.TopAndBottom;
        }
        grdProductos.DataBind();
        
    }
    protected void PopulateAssignedProductsGrid()
    {
        if (!IsPostBack)
        {
            grdAssigned.AllowPaging = true;
            grdAssigned.AllowSorting = true;
            grdAssigned.PageSize = (ConfigurationManager.AppSettings["PageSize"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageSize"]) : 10;
            grdAssigned.PagerSettings.PageButtonCount = (ConfigurationManager.AppSettings["PageButtonCount"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["PageButtonCount"]) : 5;
            grdAssigned.PagerSettings.FirstPageText = "Primero";
            grdAssigned.PagerSettings.LastPageText = "Ultimo";
            grdAssigned.PagerSettings.Mode = PagerButtons.NumericFirstLast;
            grdAssigned.PagerSettings.Position = PagerPosition.TopAndBottom;
        }
        else
        {
            grdAssigned.DataBind();
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        buildSelection();
        PopulateProductsGrid();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        buildSelection();
        List<StageDetailsTemp> products = new List<StageDetailsTemp>();
        foreach (GridViewRow item in grdProductos.Rows)
        {
            HiddenField hdnId = (HiddenField)item.FindControl("hdnProductId");
            CheckBox chkAssign = (CheckBox)item.FindControl("chkAssignProduct");
            TextBox txtQuantity = (TextBox)item.FindControl("txtQuantity");
            TextBox txtObservation = (TextBox)item.FindControl("txtObservation");
            if (chkAssign.Checked) {
                StageDetailsTemp sd = new StageDetailsTemp();
                sd.Guid = uniqueId;
                long pid = 0; 
                long.TryParse(hdnId.Value, out pid);
                sd.ProductId = pid;
                sd.StageId = StageId;
                decimal quantity = 0;
                decimal.TryParse(txtQuantity.Text, out quantity);
                sd.Quantity = quantity;
                sd.Observation = txtObservation.Text;
                sd.CreatedDate = DateTime.Now;
                products.Add(sd);
            }
        }
        grdAssigned.PageIndex = 0;
        grdProductos.PageIndex = 0;
        BLLStages bllst = new BLLStages();
        bllst.Insert_Stage_Details_Temp(products);
        PopulateAssignedProductsGrid();
        PopulateProductsGrid();
    }
    protected void btnRemove_Click(object sender, EventArgs e)
    {
        buildSelection();
        List<long> products = new List<long>();
        foreach (GridViewRow item in grdAssigned.Rows)
        {
            HiddenField hdnId = (HiddenField)item.FindControl("hdnProductId");
            CheckBox chkAssign = (CheckBox)item.FindControl("chkAssignProduct");
            if (chkAssign.Checked) {
                long pid = 0; 
                long.TryParse(hdnId.Value, out pid);
                products.Add(pid);
            }
        }
        grdAssigned.PageIndex = 0;
        grdProductos.PageIndex = 0;
        BLLStages bllst = new BLLStages();
        bllst.Delete_Stage_Details_Temp(products,uniqueId,StageId);
        PopulateAssignedProductsGrid();
        PopulateProductsGrid();
    }
    protected void grdAssigned_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        buildSelection();
    }
    protected void grdAssigned_Sorting(object sender, GridViewSortEventArgs e)
    {
        buildSelection();
    }
    protected string getObservation(object Observation)
    {
        String value = "";
        if (Observation != null)
        {
            value = Observation.ToString();
        }
        return value;
    }
    protected string getQuantity(object quantity)
    {
        String value = "";
        if (quantity != null)
        {
            decimal q = 0;
            decimal.TryParse(quantity.ToString(), out q);
            if (q < 0)
                value = "";
            else
                value = q.ToString();
        }
        return value;
    }
    protected void SetupPageByUserRoles()
    {
        List<SessionPermissions> userPermissions = new List<SessionPermissions>();
        userPermissions = (List<SessionPermissions>)Session[GlobalNames.UserPermissions];
        userPermissions = (from upb in userPermissions
                           where upb.ModuleId == (long)GlobalEnums.Modules.Procesos
                           select upb).ToList();
        if (userPermissions.Count() > 0)
        {
            foreach (SessionPermissions up in userPermissions)
            {
                if (up.PermissionId == (long)GlobalEnums.Permissions.Agregar)
                    Add = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Editar)
                    Edit = true;
                if (up.PermissionId == (long)GlobalEnums.Permissions.Ver)
                    this.View = true;
            }
            if (!View)
                this.Response.Redirect("~/Default.aspx");

            if (!Edit)
            {
                btnSave.Visible = false;
                btnAdd.Visible = false;
                btnRemove.Visible = false;
            }

        }
        else
        {
            this.Response.Redirect("~/Default.aspx");
        }
    }
   
}